package com.example.composestudy.acompainist.pager

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.launch


internal val items = "Red Green Blue".split(" ")

@OptIn(ExperimentalPagerApi::class)
@Preview(showBackground = true)
@Composable
fun PagerWithTabRowDemo() {
    val state = rememberPagerState()
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    Column {
        TabRow(selectedTabIndex = state.currentPage) {
            items.forEachIndexed { index, text ->
                Tab(
                    text = { Text(text) },
                    selected = state.currentPage == index,
                    onClick = {
                        scope.launch { state.scrollToPage(index) }
                    }
                )
            }
        }
        HorizontalPager(
            //VerticalPager(
            count = items.size,
            state = state,
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
        ) { page ->
            Box(Modifier
                .fillMaxSize()
                .background(
                    color = when (page % 3) {
                        0 -> Color.Red
                        1 -> Color.Green
                        else -> Color.Blue
                    }
                )
            )
        }
    }
    // 监听滑动状态，Toast提示当前页
    Toast.makeText(context, "当前页：${state.currentPage}", Toast.LENGTH_SHORT).show()
}